package controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pojo.User;
import service.UserService;
import tools.Constants;
import tools.PageSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.util.Date;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/userlist.html")
    public String userList(@RequestParam(value = "queryname",required = false) String queryname,
                           @RequestParam(value = "queryUserRole",required = false) Integer queryUserRole,
                           @RequestParam(value = "pageIndex",required = false)Integer currentPageNo,Model model){

        int pageSize=6;

        if (currentPageNo==null){
            currentPageNo=1;
        }

        if (queryname==null){
            queryname="";
        }
        if (queryUserRole==null){
            queryUserRole=0;
        }

        int totalCount=userService.getUserCount(queryname,queryUserRole);
        int totalPageCount=totalCount/pageSize;
        if (totalCount%pageSize!=0){
            totalPageCount++;
        }

        model.addAttribute("userList",userService.getUserList(queryname,queryUserRole,currentPageNo,pageSize));

        model.addAttribute("totalCount",totalCount);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("currentPageNo",currentPageNo);
        return "userlist";
    }


    //示例01
    @RequestMapping(value = "/useradd",method = RequestMethod.GET)
    public String addUser(
            @ModelAttribute("user")User user, HttpSession session){
        return "useradd";
    }


    @RequestMapping(value = "/addsave.html",method = RequestMethod.POST)
    public String addUserSave(User user, HttpSession session, HttpServletRequest request,
                              @RequestParam(value = "attachs",required = false)MultipartFile[] attachs){

        String idPicPath=null;
        String workPicPath=null;
        String errorInfo=null;
        boolean flag=true;
        String path=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");

        for (int i=0;i<attachs.length;i++){
            MultipartFile attach=attachs[i];
            if (!attach.isEmpty()){
                if (i==0){
                    errorInfo="uploadFileError";
                }else if (i==1){
                    errorInfo="uploadWpError";
                }
                String oldFileName=attach.getOriginalFilename();            //原文件名
                String prefix= FilenameUtils.getExtension(oldFileName);     //原文件后缀
                int filesize=1024*500;
                if (attach.getSize()>filesize){
                    request.setAttribute(errorInfo,"*上传文件不得超过500KB");
                    flag=false;
                }else if (prefix.equalsIgnoreCase("jpg")|| prefix.equalsIgnoreCase("png")||
                          prefix.equalsIgnoreCase("jpeg")|| prefix.equalsIgnoreCase("pneg")){
                    String fileName=System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal.jpg";
                    File targetFile=new File(path,fileName);
                    if (!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    try{
                        attach.transferTo(targetFile);
                    }catch (Exception e){
                        e.printStackTrace();
                        request.setAttribute(errorInfo,"*上传失败!");
                        flag=false;
                    }
                    if (i==0){
                        idPicPath=path+File.separator+fileName;
                    }else if (i==1){
                        workPicPath=path+File.separator+fileName;
                    }
                }else {
                    request.setAttribute(errorInfo,"*上传图片格式不正确!");
                    flag=false;
                }

            }
        }
        if (flag){
            User loginUser =  (User) session.getAttribute(Constants.USER_SESSION);
            user.setCreatedBy(loginUser.getId());
            user.setCreationDate(new Date());
            user.setIdPicPath(idPicPath);
            user.setWorkPicPath(workPicPath);

            boolean result = userService.add(user);

            if (result) {
                return "redirect:/user/userlist.html";
            }
        }

        return "/useradd";
    }


    @RequestMapping(value = "/view/{id}",method = RequestMethod.GET)
    public String addUserview(@PathVariable String id, Model model){

        model.addAttribute("user",userService.getUserById(id));

        return "userview";
    }

    @RequestMapping(value = "/modifty/{id}",method = RequestMethod.GET)
    public String addUsermoditfy(@PathVariable String  id , Model model){

        model.addAttribute("user",userService.getUserById(id));

        return "usermodify";
    }

    @RequestMapping(value = "/usermodifysave",method = RequestMethod.POST)
    public String addUsermoditfysave(User user, Model model){

        if (userService.modify(user)) {
            return "redirect:/user/userlist.html";
        }
        return "usermodify";

    }
    //删除用户
    @RequestMapping("/userdele")
    @ResponseBody
    public Object addUserDele(@RequestParam Integer uid){
        String result="";
        if (StringUtils.isNullOrEmpty(uid.toString())){
            result="notexist";
        }else {
            if (userService.deleteUserById(uid)) {
                result="true";
            }else{
                result="false";
            }
        }
        return JSON.toJSONString(result);


    }

    @RequestMapping("/userexist")
    @ResponseBody
    public Object getUserexist(@RequestParam String oldpassword,HttpSession session){
        String result="";
        if (StringUtils.isNullOrEmpty(oldpassword)){
            result="error";
        }else {
            User loginUser= (User) session.getAttribute(Constants.USER_SESSION);
           User user= userService.getUserById(loginUser.getId().toString());
           if (loginUser==null){
               result="sessionerror";
           }
            if (oldpassword.equals(user.getUserPassword())){
                result="true";
            }else{
                result="false";
            }

        }
        return JSON.toJSONString(result);
    }

    @RequestMapping("/pwdmodify")
    public String getUserpwd(){
        return "pwdmodify";

    }

    @RequestMapping(value = "/usermobifysave",method = RequestMethod.POST)
    public String getUserpwdmobifysave(@RequestParam("rnewpassword") String newpassword,Model model,HttpSession session){
        User loginUser= (User) session.getAttribute(Constants.USER_SESSION);
        int id=loginUser.getId();
        if (userService.updatePwd(id,newpassword)){
            model.addAttribute("message","验证成功");
        }else{
            model.addAttribute("message","验证失败");
        }
        return "pwdmodify";

    }





}
